Arrays

 

If we want to store a group of data together in one place, then an array is the data structure we should be looking for. This data structure enables us to arrange more than one element, that is why it is termed a composite data structure. In this data structure, all the elements are stored in contiguous locations of the memory. Figure 4.1 shows an array of data stored in a memory block starting at location 453.

Figure 4.1  An array of data.

Definition

An array is a finite, ordered and collection of homogeneous data elements. An array is finite because it contains only a limited number of elements, and ordered, as all the elements are stored one by one in contiguous locations of the computer memory in a linear ordered fashion. All the elements of an array are of the same data type (say, integer) only and hence it is termed a collection of homogeneous elements. The following are some examples:

     1.  An array of integers to store the age of all students in a class.

     2.  An array of strings (of characters) to store the names of all villagers in a village.

Note:   1.  An array is known as a linear data structure because all elements of the array are stored in a linear order.

          2.  The data structure is generally a built-in data type in all programming languages. The declaration syntax for an array A, say, of 100 integers in BASIC, FORTRAN, Pascal and C are as given below:

BASIC           :     DIMENSION A[100]

FORTRAN     :     DIM A[100]

Pascal            :     A: ARRAY[1...100] of integer

C                   :     int A[100]

Terminology

Size.  The number of elements in an array is called the size of the array. The size is also called length or dimension.

Type.  The type of an array represents the kind of data type it is meant for. For example, an array of integers, an array of character strings, etc.

Base.  The base of an array is the address of the memory location where the first element of the array is located. For example, 453 is the base address of the array, as depicted in Figure 2.1.

Index.  All the elements in an array can be referenced by a subscript like Ai or A[i]; this subscript is known as index. An index is always an integer value. As each array element is identified by a subscript or index, an array element is also termed subscripted or indexed variable.

Range of indices.  Indices of array elements may change from a lower bound (L) to an upper bound (U), and these bounds are called the boundaries of an array.

In a declaration of an array in FORTRAN (DIMENSION A[100]), the range of indices is from 1 to 100. For the same array in C (int A[100]) the range of indices is from 0 to 99. These are all the default ranges of indices. However, in Pascal, a user can define the range of indices from any lower bound to upper bound, for example, for A: ARRAY[–5...19] of integer, the points of the range are –5, –4, –3, ..., 18, 19. Here, the index of the ith element is –5 + i – 1. In terms of L, the lower bound, this formula stands as

                                                     Index (Ai) = L + i – 1                                                    

If the range of indices varies from L, ..., U, then the size of the array can be calculated as

                                                      Size (A) = UL + 1                                                     

Word.  Word denotes the size of an element. In each memory location, a computer can store an element of word size w, say. This word size varies from machine to machine such as 1 byte (in IBM CPU-8085) to 8 bytes (in Intel Pentium PCs). Thus, if the size of an element is doubled, then the word size of a machine to store such an element would require two consecutive memory locations.

One-Dimensional Array

If only one subscript/index is required to reference all the elements in an array, then the array is termed one-dimensional array or simply an array.

Memory Allocation for an Array

Memory representation of an array is very simple. Suppose, an array A[100] is to be stored in a memory as in Figure 2.2. Let the memory location where the first element is to be stored be M. If each element requires one word, then the location for any element say A[i] in the array can be obtained as

                                                Address (A[i]) = M + (i – 1)                                               

Figure 4.2  Physical representation of a one-dimensional array.

Likewise, in general, an array can be written as A[L ... U], where L and U denote the lower and upper bounds for the index. If the array is stored starting from the memory location M, and for each element it requires w number of words, then the address for A[i] will be

                                             Address (A[i]) = M + (iL) ´ w                                            

The above formula is known as the indexing formula, which is used to map the logical presentation of an array to physical presentation. By knowing the starting address of an array M, the location of the ith element can be calculated instead of moving towards i from M. See Figure 4.3.

Figure 4.3  Address mapping between logical and physical views of an array.

 

Operations on Arrays

Various operations that can be performed on an array are: traversing, sorting, searching, insertion, deletion, and merging.

Traversing

This operation is used to visit all elements in an array. A simplified algorithm is presented below:

Algorithm TraverseArray

Input:  An array A with elements.

Output:  According to Process( ).

Data structures:  Array A[L ... U].                                   // L and U are the lower and upper bounds

                                                                                        // of array index  

Steps:

       1.    i = L                                                                                               // Start from the first location L

       2.    While i  U do

       3.                Process(A[i])

       4.                i = i + 1                                                                            // Move to the next location

       5.    EndWhile

       6.    Stop

Note:  Here the Process() is a procedure which when called for an element can perform an action. For example, display the element on the screen, determine whether A[i] is empty or not, etc. Process( ) can also be used to manipulate some special operations such as count the special elements of interest (for example, negative numbers in an integer array), update each element of the array (say, increase each element by 10%), and so on.

Sorting

This operation, if performed on an array, will sort it in a specified order (ascending/descending). The following algorithm is used to store the elements of an integer array in ascending order.

Algorithm SortArray

Input:  An array with integer data.

Output:  An array with sorted elements in an order according to Order( ).

Data structures:  An integer array A[L...U].                   // L and U are the lower and upper bounds of

                                                                                                    // array index

Steps:

       1.        i = U

       2.        While i  L do

       3.                   j = L             // Start comparing from first

       4.                   While j < i do

       5.                             If Order(A[j], A[+ 1]) = FALSE           // If A[j] and A[j + 1] are not in order

6.                                       Swap(A[j], A[+ 1])     // Interchange the elements (see Figure 2.4)

       7.                             EndIf

       8.                             j = j + 1

       9.                   EndWhile

     10.                   i = i – 1

     11.        EndWhile

     12.        Stop

 

Here, Order(...) is a procedure to test whether two elements are in order and Swap(...) is a procedure to interchange the elements between two consecutive locations.

Figure 2.4  Swapping of two elements in an array.

 

Searching

This operation is applied to search an element of interest in an array. A simplified version of the algorithm is as follows:

Algorithm SearchArray

Input:  KEY is the element to be searched.

Output:  Index of KEY in A or a message on failure.

Data structures:  An array A[L ... U].              //L and U are the lower and upper bounds of array index

Steps:

     1.    i = L, found = 0, location = 0 // found = 0 indicates search is not finished and unsuccessful

     2.    While (i £ U) and (found = 0) do         // Continue if all or any one condition do(es) not satisfy

     3.           If Compare(A[i], KEY) = TRUE then        // If key is found

     4.                 found = 1   // Search is finished and successful

     5.                 location = i

     6.           Else

     7.                        i = i + 1 // Move to the next

     8.           EndIf  

     9.    EndWhile

  10.    If found = 0 then

  11.                  Print “Search is unsuccessful : KEY is not in the array”

  12.    Else

  13.                  Print “Search is successful : KEY is in the array at location”, location

  14.    EndIf

  15.    Return(location)

  16.    Stop

 

Insertion

This operation is used to insert an element into an array provided that the array is not full (see Figure 4.5). Let us observe the algorithmic description for the insertion operation.

Figure 4.5  Insertion of an element to an array.

Algorithm InsertArray

Input:  KEY is the item, LOCATION is the index of the element where it is to be inserted.

Output:  Array enriched with KEY.

Data structures:  An array A[... U].                              // L and U are the lower and upper bounds of

                                                                                                // array index

Steps:

     1.       If A[U] ¹ NULL then        // NULL indicates that room is available for a new entrant

     2.             Print “Array is full: No insertion possible”

     3.            Exit   // End of execution

     4.    Else

    5.                       i = U            // Start pushing from bottom

     6.             While i > LOCATION do

     7.                        A[i] = A[i–1]

     8.                        i = i – 1

     9.             EndWhile

  10.    A[LOCATION] = KEY // Put the element at the desired location

  11.    EndIf

  12.    Stop

 

 

 

Deletion

This operation is used to delete a particular element from an array. The element will be deleted by overwriting it with its subsequent element and this subsequent element then is also to be deleted. In other words, push the tail (the part of the array after the elements which are to be deleted) one stroke up. Consider the following algorithm to delete an element from an array:

Figure 4.6  Deletion of an element from an array.

Algorithm DeleteArray

Input:  KEY the element to be deleted.

Output:  Slimed array without KEY.

Data structures:  An array A[L...U].                                 // L and U are the lower and upper bounds of

                                                                  // array index

Steps:

    1.    i = SearchArray(A, KEY)       // Perform the search operation on A and return

     2.    If (i = 0) then      // the location

     3.             Print “KEY is not found: No deletion”

     4.             Exit   // Exit the program

     5.    Else

     6.             While i < U do

     7.                        A[i] = A[i + 1]      // Replace the element by its successor

     8.                        i = i + 1

     9.             EndWhile

  10.    EndIf

  11.    A[U] = NULL     // The bottom-most element is made empty (see Figure 2.6)

  12.    U = U – 1  // Update the upper bound now

  13.    Stop

 

Note:  It is a general practice that no intermediate location will be made empty, that is, an array should be packed and empty locations are at the tail of an array.

Merging

Merging is an important operation when we need to compact the elements from two different arrays into a single array (see Figure 4.7).

Figure 4.7  Merging of A1 and A2 to A.

Algorithm Merge

Input:  Two arrays A1[L1 ... U1], A2[L2 ... U2].

Output:  Resultant array A[... U], where L = L1, and U = U1 + (U2 L2 + 1) when A2 is appended after A1.

Data structures:  Array structure.   

Steps:

     1.    i1 = L1, i2 = L2,                                                                                          // Initialization of control variables

     2.    L = L1, U = U1 + U2 L2 + 1                                                    // Initialization of lower and upper bounds                                                                      

                                                                                                 // L and U are the two bounds of resultant array A                                             

     3.    i = L

     4.    AllocateMemory (Size(U L + 1))                                                   // Allocate memory for the array A

     5.    While i1 £ U1 do                                                                          // To copy array A1 into the first part of A

     6.             A[i] = A1[i1]

     7.             i = + 1, i1 = i1 + 1

     8.    EndWhile

     9.    While i2 £ U2 do                                                                           // To copy array A2 into the last part of A

  10.             A[i] = A2[i2]

  11.             i = + 1, i2 = i2 + 1

  12.    EndWhile

  13.   Stop

 

Application of Arrays

There are numerous applications of arrays in computation. This is why almost every programming language includes this data type as a built-in data type. A simple example that can be cited is to store some data before performing manipulations. Another simple example is mentioned below:

Suppose, we want to store records of all students in a class. The record structure is given by

STUDENTS

ROLL NO.

(Alphanumeric)

MARK1

(Numeric)

MARK2

(Numeric)

MARK3

(Numeric)

TOTAL

(Numeric)

GRADE

(Character)

                                                                                                                                                                        

If the sequential storage of records is not an objection, then we can store the records as shown in Figure 2.8 by maintaining 6 arrays whose size is specified by the total number of students in the class.

Figure 4.8  Storing the students’ records.

 

 

Multidimensional Arrays

So far we have discussed one-dimensional arrays. But multidimensional arrays are also important. Matrix (two-dimensional array), three-dimensional array are two examples of multidimensional arrays. The following sections describe the multidimensional arrays.

Two-dimensional Arrays

Two-dimensional arrays (alternatively termed matrices) are a collection of homogeneous elements where the elements are ordered in a number of rows and columns. An example of an m × n matrix, where m denotes the number of rows and n denotes the number of columns, is as follows:

The subscripts of any arbitrary element, say (aij), represent the ith row and jth column.

Memory representation of a matrix

Like one-dimensional arrays, matrices are also stored in contagious memory locations. There are two conventions of storing any matrix in the memory:

     1.  Row-major order

     2.  Column-major order.

In row-major order, the elements of a matrix are stored on a row-by-row basis, that is, all the elements in the first row, then in the second row, and so on. On the other hand, in column-major order, elements are stored column by column, that is, all the elements in the first column are stored in their order of rows, then in the second column, third column, and so on. For example, consider a matrix A of order 3 × 4:

This matrix can be represented in the memory as shown in Figure 4.9.

Figure 2.9  Memory representation of A3×4 matrix.

Reference of elements in a matrix

Logically, a matrix appears as two-dimensional; but physically it is stored in a linear fashion. So, in order to map from logical view to physical structure, we need an indexing formula. Obviously, the indexing formula for a different order will be different. The indexing formula, for different orders are stated below:

Row-major order.  Assume that the base address is the first location of the memory, that is, 1. So, the address of aij will be obtained as

      Address (aij) = Storing all the elements in first (i – 1)th rows

                              + the number of elements in ith row up to the jth column.

                       = (i – 1) ´ n + j

So, for the matrix A´ 4, the location of a32 will be calculated as 10 (see Figure 4.9). Instead of considering the base address to be 1, if it is at M, then the above formula can be easily modified as

                                          Address (aij) = M + (i – 1) ´ n + j – 1                                         

Column-major order.  Let us first consider that the starting location of the matrix is at memory location 1. Then

    Address (aij) = Storing all the elements in the first (j – 1)th columns

                              + the number of elements in the jth column up to the ith row

                      = (j – 1) ´ m + i

And considering the base address at M instead of 1, the above formula will get modified as

                                          Address (aij) = M + (j – 1) ´ m + i – 1                                         

Sparse Matrices

A sparse matrix is a two-dimensional array where the majority of the elements have the value null. The following is an example of a sparse matrix, where ‘*’ denotes the elements having non-null values.

 

 

In a large number of applications, sparse matrices are involved. So far as the storage of a sparse matrix is concerned, storing of null elements is nothing but wastage of memory. So, we should devise a technique such that only non-null elements will be stored. One approach is to use the linked list (this will be discussed in Chapter 3, Section 3.6.1). Some well-known sparse matrices which are symmetric in form can be classified as follows:

 

Figures 4.10(a) and 4.10(b) show the general views of sparse matrices.

Let us discuss the memory representation of some of the known forms of sparse matrices.

                             

  

ab-band matrix: non-null elements are only on a-upper diagonal and b-lower diagonal matrix

(b) Various diagonal matrices

Figure 4.10  Different symmetric sparse matrices.

Memory representation of a lower-triangular matrix

Consider the following lower-triangular matrix:

Row-major order.  According to row-major order, the address of any element aij, 1 £ i, j £ n, can be obtained as

      Address (aij) = Number of elements up to the aij element

                        = Total number of elements in the first i – 1 rows

                               + number of elements up to the jth column in the ith row

                       = 1 + 2 + 3 + ... + (i – 1) + j

                       

If the starting location of the first element, that is, of a11 is M, then the address of aij, 1 £ i, j £ n will be

              (2.7)

Column-major order.  According to column-major order, the address of any element aij, 1 £ i, j £ n can be obtained as

      Address (aij) = Number of elements up to the aij element

                       = Total number of elements in the first – 1 columns

                         + number of elements up to the ith row in the jth column

                       = [n + (n – 1) + (n – 2) + ... + (nj + 2)] + (ij + 1)

                       = {n ´ (j – 1) – [1 + 2 + 3 + ... + (j – 2) + (j – 1)] + i}

                     

                     

If the starting location of the first element (that is, of a11) is M, then the address of aij, 1 £ i, j £ n will be

Address (aij) =   (2.8)

Memory representation of an upper-triangular matrix

As an another example, consider the following form of an upper-triangular matrix:

Row-major order.  According to row-major order, the address of any element aij, 1 £ i, j £ n can be obtained as

    Address (aij) = Number of elements up to the aij element

                      = Total number of elements in the first (i – 1) rows

                        + number of elements up to the jth column in the ith row

                      = n + (n – 1) + (n – 2) + ··· + (ni + 2) + (ji + 1)

                      = n ´ (i – 1) – [1 + 2 + 3 + ··· + (i – 2) + (i – 1)] + j

                     

                     

If the starting location of the first element, i.e. of a11, is M, then the address of aij, 1 £ i, j £ n will be

               Address (aij) =                                                            

Column-major order.  According to column-major order, the address of any element aij, 1 £ i, j £ n can be obtained as

       Address (aij) = Number of elements up to the aij element

                       = Total number of elements in the first (j – 1) columns

                                + number of elements up to the ith row in the jth column

                       = [1 + 2 + 3 + ··· + (j – 1)] + i

                      

If the starting location of the first element, i.e. of a11, is M, then the address of aij, 1 £ i, j £ n will be

                                           Address (aij) =                                           

Memory representation of diagonal matrix

In sparse matrices having the elements only on the diagonal, the following points are evident:

                           Number of elements in an n ´ n square diagonal matrix = n

Any element aij can be referred in memory using the formula

                                                     Address (aij) = i [or j]

One can easily verify that the above formula is the same in both row-major order and column-major order.

Memory representation of a tridiagonal matrix

Let us consider the following tridiagonal matrix:

Row-major order.  According to row-major order, the address of any element aij, 1 £ i, j £ n can be obtained as

      Address (aij) = Number of elements up to the aij element

                       = Total number of elements in the first (i – 1) rows

                               + number of elements up to the jth column in the ith row

                      = {2 + [3 + 3 + ··· + up to (i – 2) terms]} + (ji + 2)

                      = 2 + (i – 2) ´ 3 + j – (i – 2)

                      = 2 + 2 ´ (i – 2) + j

If the starting location of the first element, i.e. of a11 is M, then the address of aij, 1 £ i, j £ n will be

                                          Address (aij) = M + 2 ´ (i – 2) + j + 1                                         

Column-major order.  According to column-major order, the address of any element aij, 1 £ i, j £ n can be obtained as

         Address (aij) = Number of elements up to the aij element

                         = Total number of elements in the first (j – 1) columns

                                 + number of elements up to the ith row in the jth column

                         = {2 + [3 + 3 + · · · + up to (j – 2) terms]} + (ij + 2)

                         = 2 + (j – 2) ´ 3 + i – (j – 2)

                         = 2 + 2 ´ (j – 2) + i

If the starting location of the first element, i.e. of a11 is M, then the address of aij, 1 £ i, j £ n will be

                                          Address (aij) = M + 2 ´ (j – 2) + i + 1                                         

Note:  The formula for row-major/column-major order is symmetric and one can be obtained from the other by interchanging i and j.

 

Three-dimensional Arrays

So far we have discussed one-dimensional and two-dimensional arrays. In some advanced applications, more than two-dimensional arrays are also used. Here, we will discuss multidimensional arrays from the theoretical point of view.

 

A three-dimensional array will look as shown in Figure 4.12.

Figure 4.12  A three-dimensional array.

A three-dimensional array can be compared with a book whereas two-dimensional and one-dimensional arrays can be compared with a page and a line, respectively. Here, the three major dimensions can be termed row, column and page. Let, for a three-dimensional array, the following specifications be known:

Number of rows = x (number of elements in a column)

Number of columns = y (number of elements in a row), and

Number of pages = z

Assume that aijk is an element in the ith row, the jth column and the kth page. Now, we are interested to find the memory location of the element aijk in the array.

Storing a 3-D array means, storing the pages one by one. Again storing a page is the same as storing a 2-D array. Thus, if the elements in a page are stored in row-major order then we term that 3-D array also in row-major order. The following formula is taking into consideration for row-major order of a 3-D array:

Address (aijk) = Number of elements in the first (k – 1) pages

                       + number of elements in the kth page up to (i – 1) rows

                       + number of elements in the kth page, in the ith row up to the jth column

                    = xy (k – 1) + (i – 1)y + j

Instead of index starting from l for all indices (as assumed in the above mentioned formula), if we assume that i changes between lx and ux, j changes between ly and uy and k changes between lz and uz, so that

                                  x = ux lx + 1,  y = uy ly + 1  and  z = uz lz + 1

Also assuming the word size of each element to be w instead of l then the above indexing formula for a 3-D array can be restated in general form as

                             Address (aijk) = M + [xy (klz) + (ilx)y + (jly)] ´ w                            

where M denotes the base address of the array.

Pointer Arrays

Some integer values, real numbers, string of characters, etc. are simple elements that arrays may contain. In addition to these, another kind of array is also well known in the theory of computer science which is in use to store the address of some memory variables or the address of other arrays. The address of a memory variable or array is known as pointer and an array containing pointers as its elements is known as pointer array. Let us consider the following example to illustrate a pointer array.

Example:  Suppose, we want to store the marks of all students of the Computer Science and Engineering (CSE) department for a year. There are six classes, say, CS1, CS2, ..., CS6. And for each class, there are at most 5 courses; for example, the course of the ith class can be denoted as CSij (where j varies from 1 to 5). We will assume that there are at most 30 students in each class.

We should maintain an array (one-dimensional) of size 6 ´ 5 ´ 30 (= 900) to store the marks. We will use pointer arrays to keep track of the marks of the ith year student in a course j(sij) and the starting location where the marks of the course CSi begin. The idea is illustrated in Figure 2.13.

Here, we have maintained three arrays, namely CLASSES, COURSES, and MARKS having sizes 6, 30 and 900, respectively. The MARKS array stores the marks obtained by the various students in different courses. The COURSES array stores the starting location for the marks of different courses. In Figure 4.13, the starting location for all the marks of CS41 course

Figure 4.13  Pointer array.

is shown by the pointed arrow. The CLASSES array points the starting location (at COURSES) for various courses under a class. For example, the location of CS41 (the first course) under the 4th year class (CS4) is shown by the pointed arrow.

Thus, if we want to retrieve the marks obtained by the kth student in the jth course of class CSi, then we have to search first the array CLASSES to obtain the starting location of all courses under class CSi. After knowing the starting location of class CSi we shall move to that location in the array COURSES. The information for the jth course can be obtained by shifting sequentially j steps in the array COURSES, where the starting location (at MARKS) for the jth course will be obtained. With that address, one can move to the referred location at MARKS array and again by sequentially moving k steps the desired marks will be retrieved.

 

 

The ArrayList class

ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large an array you need. To handle this situation, the Java Collections Framework (JCF) defines ArrayList.  The ArryList class has been added into java.util package on its JDK 1.2 version. Prior to that, a similar collection was deatlt with the Vecor class, which becomes the legacy class.

 

 

Figure 4.14. The class hierarchy of ArrayList class

 

The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this declaration:

 

class ArrayList<T> { … }

 

Here, T specifies the type of objects that the list will hold.

 

The class ArrayList has three constructors, as shown in Table 4.1.

 

Constructor

Description

ArrayList()

It is used to build an empty array list.

ArrayList(Collection<? extends T> c)

It is used to build an array list that is initialized with the elements of the collection c.

ArrayList(int capacity)

It is used to build an array list that has the specified initial capacity.

Table 4.1: Constructors in ArrayList class

 

In order to fulfill the different manipulation of such a collection, the class implements many methods. All the methods of the ArrayList class are listed in Table 4.2. All the methods are to accomplish, how to add an element, remove an element, to know the different status of the collection, that is, size, update, replicate, etc.

 

Methods of Java ArrayList

Method

Description

void add(int index, E element)

It is used to insert the specified element at the specified position in a list.

boolean add(E e)

It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends T> c)

It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.

boolean addAll(int index, Collection<? extends T> c)

It is used to append all the elements in the specified collection, starting at the specified position of the list.

void clear()

It is used to remove all of the elements from this list.

void ensureCapacity(int requiredCapacity)

It is used to enhance the capacity of an ArrayList instance.

T get(int index)

It is used to fetch the element from the particular position of the list.

boolean isEmpty()

It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o)

It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.

Object[] toArray()

It is used to return an array containing all of the elements in this list in the correct order.

<T> T[] toArray(T[] a)

It is used to return an array containing all of the elements in this list in the correct order.

Object clone()

It is used to return a shallow copy of an ArrayList.

boolean contains(Object o)

It returns true if the list contains the specified element

int indexOf(Object o)

It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.

E remove(int index)

It is used to remove the element present at the specified position in the list.

boolean remove(Object o)

It is used to remove the first occurrence of the specified element.

boolean removeAll(Collection<?> c)

It is used to remove all the elements from the list.

boolean removeIf(Predicate<? super E> filter)

It is used to remove all the elements from the list that satisfies the given predicate.

protected void removeRange(int fromIndex, int toIndex)

It is used to remove all the elements lies within the given range.

void replaceAll(UnaryOperator<E> operator)

It is used to replace all the elements from the list with the specified element.

void retainAll(Collection<?> c)

It is used to retain all the elements in the list that are present in the specified collection.

E set(int index, E element)

It is used to replace the specified element in the list, present at the specified position.

void sort(Comparator<? super E> c)

It is used to sort the elements of the list on the basis of specified comparator.

Spliterator<E> spliterator()

It is used to create spliterator over the elements in a list.

List<E> subList(int fromIndex, int toIndex)

It is used to fetch all the elements lies within the given range.

int size()

It is used to return the number of elements present in the list.

void trimToSize()

It is used to trim the capacity of this ArrayList instance to be the list's current size.

Table 4.2: Methods defined in ArrayList class

 

Creating a collection of type ArrayList

There are many ways that a collection of type ArryaList can be created. The following program few programs illustrate the use of its the constructors in this class to do the job. 

 

Example 4.1. : Simple constructor

Following program illustrates a simple use of the ArryaList() to create a collection String objects.

 

import java.util.ArrayList;

 

public class SimpleArrayListExample {

    public static void main(String[] args) {

        // Creating an ArrayList of String

        List<String> animals = new ArrayList<String>();     

 

        // Adding new elements to the ArrayList

        animals.add("Lion");

        animals.add("Tiger");

        animals.add("Cat");

        animals.add("Dog");

        // animals.add(2019);  Is it valid?

 

        // This shows how an entire collection can be dispalyed

        System.out.println(animals);     

    }

}

 

Note:

·         An ArrayList object is a collection of homogeneous objects.

·         Adding an object of another type invites compile-time error or  run-time exception.

 

Example 4.2. : Creating an ArraList object with an existing collection

Creating an ArrayList from another collection using the ArrayList(Collection c) constructor.

 

import java.util.ArrayList;

 

public class CreateArrayListFromCollectionExample {

    public static void main(String[] args) {

        // Creating a collection first. Let it be with the simple method

        ArrayList<Integer> aList = new ArrayList<>();  // Declaring aList as a collection

 

            // Adding elements into the aList collection

            aList.add(2);

            aList.add(3);

            aList.add(5);

            aList.add(7);

            aList.add(11);

 

            // Creating another collection initially with aList collection

            ArrayList<Integer> numbers = new ArrayList<Integer>(primes);

             

              // Add two more numbers into the numbers collection

              numbers.add(13);

numbers.add(17);

 

              // Now, at this stage you have two collections: aList and numbers.

               // Printing the two collections

 

                System.out.println(aList);

                System.out.println(numbers);

    }

}

 

Note:

·         You cannot add a collection of another type to a collection of other type.

·         If you create a collection of type Object, then in that collection you can add object of any type, as any other class is a child of the class Object

 

 

Example 4.3. : ArrayList of user defined objects

Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer, String, Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.

 

In the following example, you’ll learn how to create an ArrayList of user defined objects. Let the user defined type be Person

 

import java.util.ArrayList;

 

public class Person {

    private String name;

    private int age;

 

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    public void printData() {

             

}

 

public class ArrayListUserDefinedObjectExample {

    public static void main(String[] args) {

        // Declaring pList as a collection of type Person of capacity 5

        ArrayList<Person> pList = new ArrayList<Person>(3);  

        pList.add(new User("Ram", 25));

        person p2 = new Person(“Sita”, 22);   // Create a new object

        pList.add(p2);                        // add the object

        pList.add(new User("John", 34));

        pList.add(p2);                        // Duplicate entry is allowed

        pList.add(new User("Rahim", 29));     // Five objects are added

        pList.add(new User("Lilly", 24));

                            // No issue to accommodate, list grows dynamically

 

        pList.forEach(p -> {p.printData()});          

                                  // An way to access each object in a class

    }

}

 

 

Accessing an object from an ArrayList collection

You have learned how objects can be added and hence a collection can be created. Once a collection is given, you will be able to access any objects from it. The following program illustrates this.

 

Example 4.4. Accessing elements from an ArrayList.

This example shows:

·         How to check if an ArrayList is empty using the isEmpty() method.

·         How to find the size of an ArrayList using the size() method.

·         How to access the element at a particular index in an ArrayList using the get() method.

·         How to modify the element at a particular index in an ArrayList using the set() method.

 

import java.util.ArrayList;

 

public class AccessingArrayListObjects {

    public static void main(String[] args) {

        ArrayList<String> topCompanies = new ArrayList<String>();

 

        // Check if an ArrayList is empty

        System.out.println("Is the topCompanies list empty? :  " + topCompanies.isEmpty());

 

        topCompanies.add("Google");

        topCompanies.add("Apple");

        topCompanies.add("Microsoft");

        topCompanies.add("Amazon");

        topCompanies.add("Facebook");

 

        // Find the size of an ArrayList

        System.out.println("Here are the top " + topCompanies.size() +

                                               " companies in the world");

        System.out.println(topCompanies);   // Print the companies’ names

 

        // Retrieve the element at a given index

        String bestCompany = topCompanies.get(0);

        System.out.println("Best Company: " + bestCompany);

 

        String secondBestCompany = topCompanies.get(1);

        System.out.println("Second Best Company: " + secondBestCompany);

 

        String lastCompany = topCompanies.get(topCompanies.size() - 1);

        System.out.println("Last Company in the list: " + lastCompany);

 

        // Modify the element at a given index

        topCompanies.set(4, "Walmart");

        System.out.println("Modified top companies list: " + topCompanies);

    }

}

 

Insertion of objects into an ArrayList collection

You have noticed how an object can be added to a collection using add() method of the ArrayList class. There are another methods for the similar tasks, namely  addAll() and its variations. The smple add(0 method allows to one object, wheras adAll() allows to insert a list of objects.The following program illustrates the insertion operation to a collection.

 

Example 4.5.   Insertion : single, list and at specific location

 

import java.util.ArrayList;

 

public class InsertionArrayListDemo {

    public static void main(String[] args) {

        // Creating a collection first. Let it be with the simple method

        ArrayList<Integer> odd = new ArrayList<>();  // Declaring aList as a collection

 

               // Adding elements into the odd collection

               odd.add(1);

               odd.add(3);

               odd.add(5);

               odd.add(7);

               odd.add(9);

                System.out.println(odd);

 

               // Creating another collection, say number with elements from odd collection

               ArrayList<Integer> numbers = new ArrayList<Integer>(odd);

               System.out.println(numbers);    // same as odd

 

            

             // Creating another collection, say even1 

               ArrayList<Integer> even1 = new ArrayList<Integer>();

            

              // Add numbers into the even1 collection

              even1.add(2);

even1.add(4);

even1.add(6);

 

// Insert all the elements of even1 collection at the end of number collection

numbers.addAll(even1);

              System.out.println(numbers);

 

 

// Creating another collection, say any 

               ArrayList<Integer> any = new ArrayList<Integer>();

            

              // Add numbers into the any collection

              any.add(8);

any.add(11);

              any.add(13);

 

              // Add the collection any at 5-th location of the collection numbers

              numbers.addAll(5, any);

 

              //add an object at a specific location of the colletion numbers

              numbers.add(0,0);

             System.out.println(numbers);

 

 

             // what will happen to the following?

             numbers.add(100,999);       ???

    }

}

 

Deletion of elements from collection

The class ArrayList includes many methods like remove, removeAll(), clear(), etc. to remove objects from a collection. The following programs attempts to illustrates the functionalities of those methods.

 

Example 4.6. : Removing elements from an ArrayList

This program shows:

·         How to remove the element at a given index in an ArrayList | remove(int index)

·         How to remove an element from an ArrayList | remove(Object o)

·         How to remove all the elements from an ArrayList that exist in a given collection | removeAll()

·         How to remove all the elements matching a given predicate | removeIf()

·         How to clear an ArrayList | clear()

 

import java.util.ArrayList;

import java.util.function.Predicate;

 

public class DeletionArrayListDemo {

    public static void main(String[] args) {

               ArrayList<String> langs = new ArrayList<String>();  // create a collection. Initially empty

       

// Add elements into the collection

               langs.add("C");

               langs.add("C++");

               langs.add("Java");

               langs.add("Python");

               langs.add("R");

               langs.add("Spark");

 

               System.out.println("Initial List: " + langs);

 

                // Removing elements from the collection

               langs.remove(5);  // Remove the element at index `5`

               System.out.println("After remove(5): " + langs);

 

               // Remove the first occurrence of the given element from the ArrayList

              boolean status = langs.remove("Smalltalk");

              System.out.println("Smalltalk is removed : " + status);

 

               // Remove all the elements that exist in a given collection

               ArrayList<String> script = new ArrayList<String>();

               scriptingLanguages.add("SQL");

               scriptingLanguages.add("Python");

               scriptingLanguages.add("Javascript");

 

               langs.removeAll(script);    // Remove intsersection of langs and script

               System.out.println("After script removal: " + langs);

 

              // Remove all the elements that satisfy the given predicate

               langs.removeIf(new Predicate<String>() {

               @Override

               public boolean test(String s) {

                              return s.startsWith("C");

                }                                                              });

        /*

            The above removeIf() call can also be written using lambda expression like this :

            langs.removeIf(s -> s.startsWith("C"));

        */

 

        System.out.println("After Removing all elements that start with \"C\": " + langs);

 

        // Remove all elements from the ArrayList

        langs.clear();

        System.out.println("List is empty? " + langs.isEmpty());

    }

}

 

Searching an element in a collection

Searching is a frequently occurred operation when a collection is there.

 

Example 4.7. : Searching for elements in an ArrayList.

The program below shows how to:

·         Check if an ArrayList contains a given element | contains()

·         Find the index of the first occurrence of an element in an ArrayList | indexOf()

·         Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()

 

import java.util.ArrayList;

 

public class SearchElementsInArrayListExample {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<Stsring>();

        names.add("John");

        names.add("Alice");

        names.add("Bob");

        names.add("Steve");

        names.add("John");

        names.add("Steve");

        names.add("Maria");

 

        // Check if an ArrayList contains a given element

        System.out.println("Bob exist? : " + names.contains("Bob"));

 

        // Find the index of the first occurrence of an element in an ArrayList

        System.out.println("indexOf \"Steve\": " + names.indexOf("Steve"));

        System.out.println("indexOf \"Mark\": " + names.indexOf("Mark"));

 

        // Find the index of the last occurrence of an element in an ArrayList

        System.out.println("lastIndexOf John : " + names.lastIndexOf("John"));

        System.out.println("lastIndexOf Bill: " + names.lastIndexOf("Bill"));

    }

}

 

Sorting an ArrayList collection

Sorting an ArrayList is a very common task that you will encounter in your programs. In this section, I’ll show you how to

·         Sort an ArrayList using Collections.sort() method.

·         Sort an ArrayList using ArrayList.sort() method.

·         Sort an ArrayList of user defined objects with a custom comparator.

 

 

Example 4.8a. :  Sort an ArrayList using Collections.sort() method

 

 import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

 

public class ArrayListCollectionsSortExample {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        numbers.add(13);

        numbers.add(7);

        numbers.add(18);

        numbers.add(5);

        numbers.add(2);

 

        System.out.println("Before : " + numbers);

 

        // Sorting an ArrayList using Collections.sort() method

        Collections.sort(numbers);

 

        System.out.println("After : " + numbers);

    }

}

Example 4.8b. : Sort an ArrayList using ArrayList.sort() method

 

import java.util.*;

 

public class ArrayListSortExample {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();

        names.add("Lisa");

        names.add("Preeti");

        names.add("Jay");

        names.add("Soma");

 

        System.out.println("Names : " + names);

 

        // Sort an ArrayList using its sort() method.

       // You must pass a Comparator to the ArrayList.sort() method.

        names.sort(new Comparator<String>() {

            @Override

            public int compare(String name1, String name2) {

                return name1.compareTo(name2);

            }

        });

 

        /*

       The above `sort()` method call can also be written simply using

       lambda expression as shown below.

        names.sort((name1, name2) -> name1.compareTo(name2));

      */

 

        // Following is an even more concise solution

        names.sort(Comparator.naturalOrder());

 

        System.out.println("Sorted Names : " + names);

    }

}

 

Example 4.8c. : Sort an ArrayList of Objects using custom Comparator

 

import java.util.*;

 

class Person {

    private String name;

    private Integer age;

 

    public Person(String name, Integer age) {

        this.name = name;

        this.age = age;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public Integer getAge() {

        return age;

    }

 

    public void setAge(Integer age) {

        this.age = age;

    }

 

    @Override

    public String toString() {

        return "{" +

                "name='" + name + '\'' +

                ", age=" + age +

                '}';

    }

}

 

public class ArrayListObjectSortExample {

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();

        people.add(new Person("Sachin", 47));

        people.add(new Person("Chris", 34));

        people.add(new Person("Rajeev", 25));

        people.add(new Person("David", 31));

 

        System.out.println("Person List : " + people);

 

        // Sort People by their Age

        people.sort((person1, person2) -> {

            return person1.getAge() - person2.getAge();

        });

 

        // A more concise way of writing the above sorting function

        people.sort(Comparator.comparingInt(Person::getAge));

 

        System.out.println("Sorted Person List by Age : " + people);

 

        // You can also sort using Collections.sort() method by passing the custom Comparator

        Collections.sort(people, Comparator.comparing(Person::getName));

        System.out.println("Sorted Person List by Name : " + people);

    }

}

 

Traversing a collection

There are a number of methods to traverse a collection, which are illustrated in the following program.

 

Example 4.9. : Iterating over an ArrayList

The following example shows how to iterate over an ArrayList using

 

1.       forEach and lambda expression.

2.       iterator()

3.       forEachRemaining() method.

4.       listIterator().

5.       Simple for-each loop.

6.       for loop with index.

 

 

 

import java.util.ArrayList;

import java.util.Iterator;

import java.util.ListIterator;

 

public class IterateOverArrayListDemo {

    public static void main(String[] args) {

        ArrayList<String> tvShows = new ArrayList<String>();

        tvShows.add("Nimki Mukhiya");

        tvShows.add("Game of Thrones");

        tvShows.add("Mahabharat");

        tvShows.add("Balika Badhu");

 

        System.out.println("Traversing using forEach()  and lambda \n");

        tvShows.forEach(tvShow -> { System.out.println(tvShow); });

 

        System.out.println("\n=== Iterate using an iterator() ===");

        Iterator<String> tvShowIterator = tvShows.iterator();

        while (tvShowIterator.hasNext()) {

            String tvShow = tvShowIterator.next();

            System.out.println(tvShow);

        }

 

        System.out.println("Traversing usingiterator() and forEachRemaining()");

        tvShowIterator = tvShows.iterator();

        tvShowIterator.forEachRemaining(tvShow -> {

            System.out.println(tvShow);

        });

 

        System.out.println("Traversing using a listIterator() \n");

        // Here, we start from the end of the list and traverse backwards.

        ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size());

        while (tvShowListIterator.hasPrevious()) {

            String tvShow = tvShowListIterator.previous();

            System.out.println(tvShow);

        }

 

        System.out.println("\n=== Iterate using simple for-each loop ===");

        for(String tvShow: tvShows) {

            System.out.println(tvShow);

        }

 

        System.out.println("\n=== Iterate using for loop with index ===");

        for(int i = 0; i < tvShows.size(); i++) {

            System.out.println(tvShows.get(i));

        }

    }

}

 

Example 4.10.

The iterator() and listIterator() methods are useful when you need to modify the ArrayList while traversing.

 

Consider the following example, where we remove elements from the ArrayList using iterator.remove() method while traversing through it

 

import java.util.*;

 

public class ArrayListIteratorRemoveExample {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<Integer>();

        numbers.add(13);

        numbers.add(18);

        numbers.add(25);

        numbers.add(40);

 

        Iterator<Integer> numbersIterator = numbers.iterator();

        while (numbersIterator.hasNext()) {

            Integer num = numbersIterator.next();

            if(num % 2 != 0) {

                numbersIterator.remove();

            }

        }

 

        System.out.println(numbers);

    }

}

 

 

 

 

Copy a collection

When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. You can do this by calling toArray( ), which is defined by Collection. Several reasons exist why you might want to convert a collection into an array, such as:

• To obtain faster processing times for certain operations

• To pass an array to a method that is not overloaded to accept a collection

• To integrate collection-based code with legacy code that does not understand collections

 

Whatever the reason, converting an ArrayList to an array is a trivial matter. As explained earlier, there are two versions of toArray( ), which are shown again here for your convenience:

 

 Object[ ] toArray( );

 T[ ] toArray();

 

The metyhod should be called for the collection object. The first returns an array of Object. The second returns an array of elements that have the same type as T. Normally, the second form is more convenient because it returns the proper type of array.

 

Example 4.11. Obtaining an array from an ArrayList

 

import java.util.*;

class ArrayListToArray {

    public static void main(String args[]) {

        // Create an array list.

       ArrayList<Integer> al = new ArrayList<Integer>();

 

       // Add elements to the array list.

       al.add(1);

        al.add(2);

       al.add(3);

       al.add(4);

       System.out.println("Contents of al: " + al);

 

       // Get the array.

        Integer ia[] = new Integer[al.size()];

        ia = al.toArray();

 

        // Object[] ia = al.toArray();   Alternatively

       

int sum = 0;

        // Sum the array.

        for(int i : ia) sum += i;

              System.out.println("Sum is: " + sum);

       }

  }

 

Note:

If you want to copy a collection to another, that is, duplicate, then you can call the method clone(). For example, Object aCopy = al.clone(). Here, aCopy and al are the two collections.

 

 

 

Parallel access to an ArrayList collection

The ArrayList class is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes not-deterministic because one thread might override the changes done by another thread.

 

Example 4.12. : Non-Synchronizing Access to an ArrayList

 

Example Demonstrating ArrayList’s unpredictable behavior in multi-threaded environments

The following example shows what happens when multiple threads try to modify an ArrayList at the same time.

 

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

 

public class UnsafeArrayListExample {

    public static void main(String[] args) throws InterruptedException {

        List<Integer> unsafeArrayList = new ArrayList<>();

        unsafeArrayList.add(1);

        unsafeArrayList.add(2);

        unsafeArrayList.add(3);

 

        // Create a thread pool of size 10

        ExecutorService executorService = Executors.newFixedThreadPool(10);

 

        // Create a Runnable task that increments each element of the ArrayList by one

        Runnable task = () -> {

            incrementArrayList(unsafeArrayList);

        };

 

        // Submit the task to the executor service 100 times.

        // All the tasks will modify the ArrayList concurrently

        for(int i = 0; i < 100; i++) {

            executorService.submit(task);

        }

 

        executorService.shutdown();

        executorService.awaitTermination(60, TimeUnit.SECONDS);

 

        System.out.println(unsafeArrayList);

    }

 

    // Increment all the values in the ArrayList by one

    private static void incrementArrayList(List<Integer> unsafeArrayList) {

        for(int i = 0; i < unsafeArrayList.size(); i++) {

            Integer value = unsafeArrayList.get(i);

            unsafeArrayList.set(i, value + 1);

        }

    }

}

 

The final output of the above program should be equal to [101, 102, 103] because we’re incrementing the values in the ArrayList 100 times. But if you run the program, it will produce different output every time it is run -

 

Try running the above program multiple times and see how it produces different outputs. To learn more about such issues in multi-threaded programs, check out my article on Java Concurrency Issues and Thread Synchronization.

 

Example 4.13. : Synchronizing Access to an ArrayList

Example demonstrating how to synchronize concurrent modifications to an ArrayList

All right! Now let’s see how we can synchronize access to the ArrayList in multi-threaded environments.

 

The following example shows the synchronized version of the previous example. Unlike the previous program, the output of this program is deterministic and will always be the same.

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

 

public class SynchronizedArrayListExample {

    public static void main(String[] args) throws InterruptedException {

        List<Integer> safeArrayList = Collections.synchronizedList(new ArrayList<>());

        safeArrayList.add(1);

        safeArrayList.add(2);

        safeArrayList.add(3);

 

        // Create a thread pool of size 10

        ExecutorService executorService = Executors.newFixedThreadPool(10);

 

        // Create a Runnable task that increments each element of the ArrayList by one

        Runnable task = () -> {

            incrementArrayList(safeArrayList);

        };

 

        // Submit the task to the executor service 100 times.

        // All the tasks will modify the ArrayList concurrently

        for(int i = 0; i < 100; i++) {

            executorService.submit(task);

        }

 

        executorService.shutdown();

        executorService.awaitTermination(60, TimeUnit.SECONDS);

 

        System.out.println(safeArrayList);

    }

 

    // Increment all the values in the ArrayList by one

    private static void incrementArrayList(List<Integer> safeArrayList) {

        synchronized (safeArrayList) {

            for (int i = 0; i < safeArrayList.size(); i++) {

                Integer value = safeArrayList.get(i);

                safeArrayList.set(i, value + 1);

            }

        }

    }

}

 

The above example uses Collections.synchronizedList() method to get a synchronized view of the ArrayList.

 

Moreover, the modifications to the ArrayList inside the incrementArrayList() method is wrapped inside a synchronized block. This ensures that no two threads can increment ArrayList elements at the same time.

 

You can also use a CopyOnWriteArrayList if you need thread safety. It is a thread-safe version of the ArrayList class. It implements all the mutating operations by making a fresh copy of the ArrayList.

 

 

Note:

·         The ArrayList is slower than standard arrays because a lot of shifting needs to occur if any element is removed from the array list.

·         Dynamic arrays are also supported by the legacy class Vector.

·         In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size.

·         Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk.

·         The ArrayList class can contain duplicate elements.

·         The ArrayList class maintains insertion order.

·         The ArrayList class is non-synchronized. If multiple programs access the same ArryaList, then the consistent result is not guaranteed.

·         The ArrayList allows random access because array works at the index basis.

 

 

The Arrays class

The Arrays class is a part of the Java Collection framework defined in java.util package. The class hierarchy and its declaration in java.ytil package is as follows.

 

 

Its name is in plural form “Arrays” because it can handle java arrays of different primitive types like byte, char, short, int, long, float, double, and universal type Object. In fact, this class Arrays has been designed to bridge the gap between collections and java arrays. More specifically, there are often times when loops are used to do some tasks on an array like fill an array with a particular value, sort an array, search in an array, etc.

 

 

 

This class provides several static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. That is, no object of the class Arrays need to be created to access a method in it. The following is the syntax to access a method in Arrays.

 

Arrays.<methodName (. . .)>;

 

The several methods of Arrays class are listed in Table 10. Since all methods are static, it is not mentioned explicitly in each method specification in Table 10.<T> denotes a type parameter. This type parameter includes Boolean, byte, char, short, int, long, float, double, and Object.

 

Method

Description

<T>ListasList(<T> array)

It returns a List that is backed by an array of type T. Both the list and array refer to the same location.

intbinarySearch(<T> array[ ], <T> value)

It searches for the specified element in the array with the help of Binary Search algorithm. It returns the index of an array location, if found else NULL. Array of type boolean is not applicable to such a method.

<T>[ ] copyOf(<T>[ ] source, intlen)

It returns a copy of an array source and len is the length of the copy. If thecopy is longer than source, then the copy is padded with zeros (for numeric arrays), nulls(for object arrays), or false (for boolean arrays). If the copy is shorter than source, thenthe copy is truncated.

<T>[ ] copyOfRange(<T>[ ] source, int start, int end)

It returns a copy of a range within an array in from start to end-1.

boolean equals(<T> array1[ ], <T> array2 [ ])

It returns true if two arrays are equivalent, otherwise, it returnsfalse.Here, array1 and array2 should be comparable for equality.

booleandeepEquals(Object[ ] a, Object[ ] b)

Themethod can be used to determine if two arrays, which might containnested arrays, are equal.

void fill(<T> array[ ], <T> value)

It fills anarray with a specified value.

void fill(<T> array[ ], int start, int end, <T> value)

It fills anarray with a specified value to a subset of an array from position start to end-1.

void sort(byte array[ ])

It sorts an array so that it is arranged in ascending order.

void sort(<T> array[ ], int start, int end)

It sorts a subarray in ascending order  between the position start and end-1.

void parallelSort(byte array[ ])

it sorts, into ascending order, portions of an array in parallel and then merges theresults.

void parallelSort(<T> array[ ], int start, int end)

It sorts a subarray in ascending order  between the position start and end-1 in parallel.

<T>Spliteratorspliterator(T array[ ])

It returns a spliterator to an entire array. Here, array is the array that the spliterator will cycle through.

<T>Spliteratorspliterator(T array[ ], int start, int end)

It enables you to specify a range to iterate within the array.

<T> Stream stream(T array[ ])

It supports a Stream interface. Here, array is the array to which the stream will refer.

<T> Stream stream(<T> array[ ], int start, int end)

It supports a Stream interface within a spefic range from the position stat to end-1.

void setAll(double array[ ], IntToDoubleFunction<? extends T>genVal)

It assigns values to all of the elements of the array. Other overloading method exist to dealy with arrays of int, long, and generic.

void parallelSetAll(double array[ ],

IntToDoubleFunction<? extends T>genVal)

It does the saem thing as setAll(…) but in parallel.

void parallelPrefix(double array[ ], DoubleBinaryOperatorfunc)

it modifies an array so that each element contains the cumulativeresult of an operation applied to all previous elements. For example, if the operation is

addition, then on return, the array elements will contain the values associated withthe running sum of the original values.Many otherversions are provided, including those that operate on types int, long, and generic, andthose that let you specify a range within the array on which to operate.

Note: Arrays also provides toString( ) and hashCode( ) for the various types of arrays. Inaddition, deepToString( ) and deepHashCode( ) are provided, which operate effectively onarrays that contain nested arrays.

Table 4.10: Methods defined in Arrays class.

 

In the following, some simple programs are given to illustrating the utilities of the class Arrays.

 

Converting an array into a collection

 

Example 4.14.

This program illustrates the use of asList() method.

 

  

import java.util.Arrays;

 

public class Main {

      public static void main(String[] args)  {

 

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

 

        // To convert the elements as List

        System.out.println("Integer Array as List: "

                           + Arrays.asList(intArr));

      }

}

 

Example 4.15.

This program illustrates the use of copyOf() method.

 

// Java program to demonstrate Arrays.copyOf() method

  

importjava.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        intintArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

  

        System.out.println("\nNew Arrays by copyOf:\n");

  

        System.out.println("Integer Array: "

                           + Arrays.toString(

                                 Arrays.copyOf(intArr, 10)));

    }

}

 

Example 4.16.

This program illustrates the use of Arrays.copyOfRange() method

  

Import java.util.Arrays;

  

Public class Main {

    Public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

  

        System.out.println("\nNew Arrays by copyOfRange:\n");

  

        // To copy the array into an array of new length

        System.out.println("Integer Array: "

                           + Arrays.toString(

                                 Arrays.copyOfRange(intArr, 1, 3)));

    }

}

 

Example 4.17.

This method returns a String representation of the contents of this Arrays. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function.

 

Import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        Int intArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Searching an array

 

Example 4.18.

This program illustrates the use of Binary Search method.

 

// Java program to demonstrate Arrays.binarySearch() method

  

Import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        Arrays.sort(intArr);

  

        Int intKey = 22;

  

        System.out.println(intKey

                           + " found at index = "

                           + Arrays

                                 .binarySearch(intArr, intKey));

    }

}

 

Example 4.19.

This program illustrates the use of Binary Search method within a sublist.

// Java program to demonstrate Arrays.binarySearch() method

  

Import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        intintArr[] = { 10, 20, 15, 22, 35};

  

        Arrays.sort(intArr);

  

        int intKey = 22;

  

        System.out.println(

            intKey

            + " found at index = "

            + Arrays.binarySearch(intArr, 1, 3, intKey));

    }

}

 

Sorting an array

Example 4.20.

This program illustrates the use  of sorting the complete array in ascending order.

 

import java.util.Arrays;

 

public class Main13 {

    public static void main(String[] args)

    {

 

        // Get the Array

int intArr[] = { 10, 20, 15, 22, 35 };

 

        // To sort the array using normal sort-

Arrays.sort(intArr);

 

System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.21.

This program illustrates the use  ofArrays.parallelSort() method

  

Import java.util.Arrays;

  

Public class Main {

    Public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using parallelSort

        Arrays.parallelSort(intArr);

  

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.22.

This program illustrates the use  of sorting the complete array in ascending order using second version of Arrays.sort() method

  

Import java.util.Arrays;

  

Public class Main {

    Public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        Arrays.sort(intArr, 1, 3);

  

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.23.

This method sorts the specified array of objects according to the order induced by the specified comparator.

// Java program to demonstrate working of Comparator

// interface

import java.util.*;

import java.lang.*;

import java.io.*;

  

// A class to represent a student.

class Student {

    introllno;

    String name, address;

  

    // Constructor

    public Student(int rollno, String name, String address)

    {

        this.rollno = rollno;

        this.name = name;

        this.address = address;

    }

  

    // Used to print student details in main()

    Public String toString()

    {

        return this.rollno + " "

            + this.name + " "

            + this.address;

    }

}

 

class Sortbyroll implements Comparator<Student> {

  

    // Used for sorting in ascending order of

    // roll number

    public int compare(Student a, Student b)

    {

        return a.rollno - b.rollno;

    }

}

  

// Driver class

Class Main {

    public static void main(String[] args)

    {

        Student[] arr = { newStudent(111, "bbbb", "london"),

                          newStudent(131, "aaaa", "nyc"),

                          newStudent(121, "cccc", "jaipur") };

  

        System.out.println("Unsorted");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

  

        Arrays.sort(arr, newSortbyroll());

  

        System.out.println("\nSorted by rollno");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

    }

}

 

 

Traversal techniques

Example 4.24.

This program illustrates the use  ofComparator interface

importjava.util.*;

importjava.lang.*;

importjava.io.*;

  

// A class to represent a student.

Class Student {

    int rollno;

    String name, address;

  

    // Constructor

    public Student(int rollno, String name, String address)

    {

        this.rollno = rollno;

        this.name = name;

        this.address = address;

    }

  

    // Used to print student details in main()

    public String toString()

    {

        return this.rollno + " "

            + this.name + " "

            + this.address;

    }

}

  

class Sortbyroll implements Comparator<Student> {

    // Used for sorting in ascending order of

    // roll number

    public int compare(Student a, Student b)

    {

        return a.rollno - b.rollno;

    }

}

 

// Driver class

class Main {

    public static void main(String[] args)

    {

        Student[] arr = { newStudent(111, "bbbb", "london"),

                          newStudent(131, "aaaa", "nyc"),

                          newStudent(121, "cccc", "jaipur") };

  

        System.out.println("Unsorted");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

  

        Arrays.sort(arr, 1, 2, newSortbyroll());

  

        System.out.println("\nSorted by rollno");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

    }

}

 

Example 4.25.

This method returns a Spliterator covering all of the specified Arrays.

 

Import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        System.out.println("Integer Array: "

                           + Arrays.spliterator(intArr));

    }

}

 

 

Example 4.26.

This method returns a Spliterator of the type of the array covering the specified range of the specified Arrays.

 

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        System.out.println("Integer Array: "

                           + Arrays.spliterator(intArr, 1, 3));

    }

}

 

Miscellaneous operations

 

Example 4.27.

This program illustrates the use of Arrays.deepEquals() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // Get the second Arrays

        int intArr1[][] = { { 10, 15, 22} };

  

        // To compare both arrays

        System.out.println("Integer Arrays on comparison: "

                           + Arrays.deepEquals(intArr, intArr1));

    }

}

 

 

 

Example 4.28.

This program illustrates the use of Arrays.deepHashCode() method

  

import java.util.Arrays;

  

public class Main {

    public  static void main(String[] args)

    {

  

        // Get the Array

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // To get the dep hashCode of the arrays

        System.out.println("Integer Array: "

                           + Arrays.deepHashCode(intArr));

    }

}

 

 

Example 4.29.

This program illustrates the use of Arrays.deepToString() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // To get the deep String of the arrays

        System.out.println("Integer Array: "

                           + Arrays.deepToString(intArr));

    }

}

 

 

Example 4.30.

This program illustrates the use of Arrays.equals() method

  

import java.util.Arrays;

  

publicclassMain {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // Get the second Arrays

        int intArr1[] = { 10, 15, 22};

  

        // To compare both arrays

        System.out.println("Integer Arrays on comparison: "

                           + Arrays.equals(intArr, intArr1));

    }

}

 

 

Example 4.31.

This program illustrates the use of Arrays.fill() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[] = { 10, 20, 15, 22, 35};

  

        int intKey = 22;

  

        Arrays.fill(intArr, intKey);

  

        // To fill the arrays

        System.out.println("Integer Array on filling: "

                           + Arrays.toString(intArr));

    }

}

 

 

Example 4.32.

This program illustrates the use of  Arrays.hashCode() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To get the hashCode of the arrays

        System.out.println("Integer Array: "

                           + Arrays.hashCode(intArr));

    }

}

 

 

 

 

Example 4.33.

This method returns a sequential stream with the specified array as its source.

 

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To get the Stream from the array

        System.out.println("Integer Array: "

                           + Arrays.stream(intArr));

    }

}

 

 

The Arrays class

The Arrays class is a part of the Java Collection framework defined in java.util package. The class hierarchy and its declaration in java.ytil package is as follows.

 

 

Its name is in plural form “Arrays” because it can handle java arrays of different primitive types like byte, char, short, int, long, float, double, and universal type Object. In fact, this class Arrays has been designed to bridge the gap between collections and java arrays. More specifically, there are often times when loops are used to do some tasks on an array like fill an array with a particular value, sort an array, search in an array, etc.

 

 

 

This class provides several static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. That is, no object of the class Arrays need to be created to access a method in it. The following is the syntax to access a method in Arrays.

 

Arrays.<methodName (. . .)>;

 

The several methods of Arrays class are listed in Table 10. Since all methods are static, it is not mentioned explicitly in each method specification in Table 10.<T> denotes a type parameter. This type parameter includes Boolean, byte, char, short, int, long, float, double, and Object.

 

Method

Description

<T>ListasList(<T> array)

It returns a List that is backed by an array of type T. Both the list and array refer to the same location.

intbinarySearch(<T> array[ ], <T> value)

It searches for the specified element in the array with the help of Binary Search algorithm. It returns the index of an array location, if found else NULL. Array of type boolean is not applicable to such a method.

<T>[ ] copyOf(<T>[ ] source, intlen)

It returns a copy of an array source and len is the length of the copy. If thecopy is longer than source, then the copy is padded with zeros (for numeric arrays), nulls(for object arrays), or false (for boolean arrays). If the copy is shorter than source, thenthe copy is truncated.

<T>[ ] copyOfRange(<T>[ ] source, int start, int end)

It returns a copy of a range within an array in from start to end-1.

boolean equals(<T> array1[ ], <T> array2 [ ])

It returns true if two arrays are equivalent, otherwise, it returnsfalse.Here, array1 and array2 should be comparable for equality.

booleandeepEquals(Object[ ] a, Object[ ] b)

Themethod can be used to determine if two arrays, which might containnested arrays, are equal.

void fill(<T> array[ ], <T> value)

It fills anarray with a specified value.

void fill(<T> array[ ], int start, int end, <T> value)

It fills anarray with a specified value to a subset of an array from position start to end-1.

void sort(byte array[ ])

It sorts an array so that it is arranged in ascending order.

void sort(<T> array[ ], int start, int end)

It sorts a subarray in ascending order  between the position start and end-1.

void parallelSort(byte array[ ])

it sorts, into ascending order, portions of an array in parallel and then merges theresults.

void parallelSort(<T> array[ ], int start, int end)

It sorts a subarray in ascending order  between the position start and end-1 in parallel.

<T>Spliteratorspliterator(T array[ ])

It returns a spliterator to an entire array. Here, array is the array that the spliterator will cycle through.

<T>Spliteratorspliterator(T array[ ], int start, int end)

It enables you to specify a range to iterate within the array.

<T> Stream stream(T array[ ])

It supports a Stream interface. Here, array is the array to which the stream will refer.

<T> Stream stream(<T> array[ ], int start, int end)

It supports a Stream interface within a spefic range from the position stat to end-1.

void setAll(double array[ ], IntToDoubleFunction<? extends T>genVal)

It assigns values to all of the elements of the array. Other overloading method exist to dealy with arrays of int, long, and generic.

void parallelSetAll(double array[ ],

IntToDoubleFunction<? extends T>genVal)

It does the saem thing as setAll(…) but in parallel.

void parallelPrefix(double array[ ], DoubleBinaryOperatorfunc)

it modifies an array so that each element contains the cumulativeresult of an operation applied to all previous elements. For example, if the operation is

addition, then on return, the array elements will contain the values associated withthe running sum of the original values.Many otherversions are provided, including those that operate on types int, long, and generic, andthose that let you specify a range within the array on which to operate.

Note: Arrays also provides toString( ) and hashCode( ) for the various types of arrays. Inaddition, deepToString( ) and deepHashCode( ) are provided, which operate effectively onarrays that contain nested arrays.

Table 4.16: Methods defined in Arrays class.

 

In the following, some simple programs are given to illustrating the utilities of the class Arrays.

 

Converting an array into a collection

 

Example 4.34.

This program illustrates the use of asList() method.

 

  

import java.util.Arrays;

 

public class Main {

      public static void main(String[] args)  {

 

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

 

        // To convert the elements as List

        System.out.println("Integer Array as List: "

                           + Arrays.asList(intArr));

      }

}

 

Example 4.35.

This program illustrates the use of copyOf() method.

 

// Java program to demonstrate Arrays.copyOf() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

  

        System.out.println("\nNew Arrays by copyOf:\n");

  

        System.out.println("Integer Array: "

                           + Arrays.toString(

                                 Arrays.copyOf(intArr, 10)));

    }

}

 

Example 4.36.

This program illustrates the use of Arrays.copyOfRange() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

  

        System.out.println("\nNew Arrays by copyOfRange:\n");

  

        // To copy the array into an array of new length

        System.out.println("Integer Array: "

                           + Arrays.toString(

                                 Arrays.copyOfRange(intArr, 1, 3)));

    }

}

 

Example 4.37.

This method returns a String representation of the contents of this Arrays. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function.

 

import java.util.Arrays;

  

public class Main {

    publicstaticvoidmain(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To print the elements in one line

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

 

Searching an array

 

Example 4.38.

This program illustrates the use of Binary Search method.

 

// Java program to demonstrate Arrays.binarySearch() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        Arrays.sort(intArr);

  

        int intKey = 22;

  

        System.out.println(intKey

                           + " found at index = "

                           + Arrays

                                 .binarySearch(intArr, intKey));

    }

}

 

Example 4.38.

This program illustrates the use of Binary Search method within a sublist.

// Java program to demonstrate Arrays.binarySearch() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        Arrays.sort(intArr);

  

        int intKey = 22;

  

        System.out.println(

            intKey

            + " found at index = "

            + Arrays.binarySearch(intArr, 1, 3, intKey));

    }

}

 

Sorting an array

Example 4.39.

This program illustrates the use  of sorting the complete array in ascending order.

 

import java.util.Arrays;

 

public class Main13 {

    public static void main(String[] args)

    {

 

        // Get the Array

int intArr[] = { 10, 20, 15, 22, 35 };

 

        // To sort the array using normal sort-

Arrays.sort(intArr);

 

System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.40.

This program illustrates the use  ofArrays.parallelSort() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using parallelSort

        Arrays.parallelSort(intArr);

  

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.41.

This program illustrates the use  of sorting the complete array in ascending order using second version of Arrays.sort() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        Arrays.sort(intArr, 1, 3);

  

        System.out.println("Integer Array: "

                           + Arrays.toString(intArr));

    }

}

 

Example 4.42.

This method sorts the specified array of objects according to the order induced by the specified comparator.

// Java program to demonstrate working of Comparator

// interface

import java.util.*;

import java.lang.*;

import java.io.*;

  

// A class to represent a student.

Class Student {

    int rollno;

    String name, address;

  

    // Constructor

    public Student(introllno, String name,

                   String address)

    {

        this.rollno = rollno;

        this.name = name;

        this.address = address;

    }

  

    // Used to print student details in main()

    public String toString()

    {

        returnthis.rollno + " "

            + this.name + " "

            + this.address;

    }

}

 

class Sortbyroll implementsComparator<Student> {

  

    // Used for sorting in ascending order of

    // roll number

    public int compare(Student a, Student b)

    {

        return a.rollno - b.rollno;

    }

}

  

// Driver class

class Main {

    public static void main(String[] args)

    {

        Student[] arr = { newStudent(111, "bbbb", "london"),

                          newStudent(131, "aaaa", "nyc"),

                          newStudent(121, "cccc", "jaipur") };

  

        System.out.println("Unsorted");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

  

        Arrays.sort(arr, newSortbyroll());

  

        System.out.println("\nSorted by rollno");

        for(inti = 0; i<arr.length; i++)

            System.out.println(arr[i]);

    }

}

 

 

Traversal techniques

Example 4.43.

This program illustrates the use  ofComparator interface

import java.util.*;

import java.lang.*;

import java.io.*;

  

// A class to represent a student.

class Student {

    int rollno;

    String name, address;

  

    // Constructor

    public Student(int rollno, String name, String address)

    {

        this.rollno = rollno;

        this.name = name;

        this.address = address;

    }

  

    // Used to print student details in main()

    public String toString()

    {

        return this.rollno + " "

            + this.name + " "

            + this.address;

    }

}

  

class Sortbyroll implements Comparator<Student> {

    // Used for sorting in ascending order of

    // roll number

    publicintcompare(Student a, Student b)

    {

        returna.rollno - b.rollno;

    }

}

 

// Driver class

class Main {

    public static void main(String[] args)

    {

        Student[] arr = { newStudent(111, "bbbb", "london"),

                          newStudent(131, "aaaa", "nyc"),

                          newStudent(121, "cccc", "jaipur") };

  

        System.out.println("Unsorted");

        for(int i = 0; i<arr.length; i++)

            System.out.println(arr[i]);

  

        Arrays.sort(arr, 1, 2, newSortbyroll());

  

        System.out.println("\nSorted by rollno");

        for(int i = 0; i<arr.length; i++)

            System.out.println(arr[i]);

    }

}

 

Example 4.44.

This method returns a Spliterator covering all of the specified Arrays.

 

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        System.out.println("Integer Array: "

                           + Arrays.spliterator(intArr));

    }

}

 

 

Example 4.45.

This method returns a Spliterator of the type of the array covering the specified range of the specified Arrays.

 

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To sort the array using normal sort

        System.out.println("Integer Array: "

                           + Arrays.spliterator(intArr, 1, 3));

    }

}

 

Miscellaneous operations

 

Example 4.46.

This program illustrates the use of Arrays.deepEquals() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // Get the second Arrays

        int intArr1[][] = { { 10, 15, 22} };

  

        // To compare both arrays

        System.out.println("Integer Arrays on comparison: "

                           + Arrays.deepEquals(intArr, intArr1));

    }

}

 

 

Example 4.47.

This program illustrates the use of Arrays.deepHashCode() method

  

import java.util.Arrays;

  

public  classMain {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // To get the dep hashCode of the arrays

        System.out.println("Integer Array: "

                           + Arrays.deepHashCode(intArr));

    }

}

 

 

Example 4.48.

This program illustrates the use of Arrays.deepToString() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[][] = { { 10, 20, 15, 22, 35} };

  

        // To get the deep String of the arrays

        System.out.println("Integer Array: "

                           + Arrays.deepToString(intArr));

    }

}

 

 

Example 4.49.

This program illustrates the use of Arrays.equals() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // Get the second Arrays

        int intArr1[] = { 10, 15, 22};

  

        // To compare both arrays

        System.out.println("Integer Arrays on comparison: "

                           + Arrays.equals(intArr, intArr1));

    }

}

 

 

Example 4.50.

This program illustrates the use of Arrays.fill() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Arrays

        int intArr[] = { 10, 20, 15, 22, 35};

  

        int intKey = 22;

  

        Arrays.fill(intArr, intKey);

  

        // To fill the arrays

        System.out.println("Integer Array on filling: "

                           + Arrays.toString(intArr));

    }

}

 

 

Example 4.51.

This program illustrates the use of  Arrays.hashCode() method

  

import java.util.Arrays;

  

public class Main {

    public static void main(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To get the hashCode of the arrays

        System.out.println("Integer Array: "

                           + Arrays.hashCode(intArr));

    }

}

 

 

Example 4.52.

This method returns a sequential stream with the specified array as its source.

 

import java.util.Arrays;

  

public class Main {

    public static voidmain(String[] args)

    {

  

        // Get the Array

        int intArr[] = { 10, 20, 15, 22, 35};

  

        // To get the Stream from the array

        System.out.println("Integer Array: "

                           + Arrays.stream(intArr));

    }

}

The Vector class

There are some popular Java utility classes, which are either obsolete or deprecated. Still they are ustilized in many Collection framework classes, and this is why JDK 5 has retrofitted them.  Such classes are called legacy classes.

The following are the legacy classes defined in java.util package.

 

·         Dictionary

·         Hashtable

·         Propertioe

·         Stack

·         Vector

 

Also, there is a legacy interface called Enumeration. Each legacy classes implements the Enumeration interface and it’s composition should be learned first.

 

The Enumeration interface

Enumeration means obtaining elements from a collection one at a time. The Enumeration interface defines the methods by which you can enumerate the elements in a collection of objects. The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superseded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes (such as Vector and Properties) and is used by several other API classes. Because it is still in use, it was retrofitted for generics by JDK 5. It has this declaration:

 

interface Enumeration<T> { … }

 

where T specifies the type of element being enumerated.

 

The methods declared by Enumeration interface are summarized in Table 4.17.

 

Method

Description

boolean hasMoreElements( )

Returns true while there are still more elements to extract.

T nextElement( )

Returns the next object in the enumeration.

Table 4.17. The methods declared in Enumeration interface

 

The Vector is same as the ArrayList class, where it implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. In addition to this there the following main difference between the Vector and ArrayList classes.

 

·        Vector is synchronized.

·        Vector contains many legacy methods that are not part of the collections framework.

·        It extends AbstractList and implements List interfaces.

 

Following is the list of four constructors in the class Vector (Table 4.18).

Constructor

Description

Vector( )

This constructor creates a default vector, which has an initial size of 10.

Vector(int size)

This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size.

Vector(int size, int incr)

This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward.

Vector(Collection c)

This constructor creates a vector that contains the elements of collection c.

Table 4.18. The constructors of Vector class

 

All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. By allocating more than just the required memory, the vector reduces the number of allocations that must take place as the vector grows. This reduction is important, because allocations are costly in terms of time. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. If you don’t specify an increment, the vector’s size is doubled by each allocation cycle.

 

Vector defines the following data members with protected access specifier:

 

int capacityIncrement;

int elementCount;

Object[ ] elementData;

 

The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. The array that holds the vector is stored in elementData.

 

Apart from the methods inherited from its parent classes, that is AbstractList and List, Vector defines the following legacy methods (Table 4.19).

 

 

Method

Description

void addElement(E element)

The object specified by element is added to the vector.

int capacity( )

Returns the capacity of the vector.

Object clone( )

Returns a duplicate of the invoking vector.

boolean contains(Object element)

Returns true if element is contained by the vector, and returns false if it is not.

void copyInto(Object array[ ])

The elements contained in the invoking vector are copied into the array specified by array.

E elementAt(int index)

Returns the element at the location specified by index.

Enumeration<E> elements( )

Returns an enumeration of the elements in the vector.

void ensureCapacity(int size)

Sets the minimum capacity of the vector to size.

E firstElement( )

Returns the first element in the vector.

int indexOf(Object element)

Returns the index of the first occurrence of element. If the object is not in the vector, –1 is returned.

 

Method

Description

int indexOf(Object element, int start)

Returns the index of the first occurrence of element at or after start. If the object is not in that portion of the vector, –1 is returned.

void insertElementAt(E element,

int index)

Adds element to the vector at the location specified by index.

boolean isEmpty( )

Returns true if the vector is empty, and returns false if it contains one or more elements.

E lastElement( )

Returns the last element in the vector.

int lastIndexOf(Object element)

Returns the index of the last occurrence of element. If the object is not in the vector, –1 is returned.

int lastIndexOf(Object element,

int start)

Returns the index of the last occurrence of element before start. If the object is not in that portion of the vector, –1 is returned.

void removeAllElements( )

Empties the vector. After this method executes, the size of the vector is zero.

boolean removeElement(Object element)

Removes element from the vector. If more than one instance of the specified object exists in the vector, then it is the first one that is removed. Returns true if successful and false if the object is not found.

void removeElementAt(int index)

Removes the element at the location specified by index.

void setElementAt(E element,

int index)

The location specified by index is assigned element.

void setSize(int size)

Sets the number of elements in the vector to size. If the new size is less than the old size, elements are lost. If the new size is larger than the old size, null elements are added.

int size( )

Returns the number of elements currently in the vector.

String toString( )

Returns the string equivalent of the vector.

void trimToSize( )

Sets the vector’s capacity equal to the number of elements that it currently holds.

Table 4.19. Legacy methods defined in Vector class

 

In the following, we wrote a number of small programs to illustrating the usefulness of different method in the Vector class.

 

Creating vectors

The constructors are well defined in the Vector class, which can be used to create vector as a collection.

Constructor

Description

Vector( )

This constructor creates a default vector, which has an initial size of 10.

Vector(int size)

This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size.

Vector(int size, int incr)

This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward.

Vector(Collection c)

This constructor creates a vector that contains the elements of collection c.

Table 4.20. The constructors used to create a collection of type Vector

 

Example 4.53.

The following program illustrates add() method .

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg) { 

        Vector v = new Vector();  // create a default vector of size 10

  

        v.add(1);

        v.add(2);

        v.add("Debasis");

  v.add(3.4); 

        v.add("Samanta");  

        System.out.println("Vector is " + v);

    }

}

 

Example 4.54.

The following program uses a vector to store various types of numeric objects. It demonstrates several of the legacy methods defined by Vector. It also demonstrates the Enumeration interface.

 

import java.util.*;

 

public class VectorDemo {

 

   public static void main(String args[]) {

      // initial size is 3, increment is 2

      Vector v = new Vector(3, 2);

      System.out.println("Initial size: " + v.size());

      System.out.println("Initial capacity: " + v.capacity());

     

      v.addElement(new Integer(1));

      v.addElement(new Integer(2));

      v.addElement(new Integer(3));

      v.addElement(new Integer(4));

      System.out.println("Capacity after four additions: " + v.capacity());

 

      v.addElement(new Double(5.45));

      System.out.println("Current capacity: " + v.capacity());

     

      v.addElement(new Double(6.08));

      v.addElement(new Integer(7));

      System.out.println("Current capacity: " + v.capacity());

     

      v.addElement(new Float(9.4));

      v.addElement(new Integer(10));

      System.out.println("Current capacity: " + v.capacity());

     

      v.addElement(new Integer(11));

      v.addElement(new Integer(12));

      System.out.println("First element: " + (Integer)v.firstElement());

      System.out.println("Last element: " + (Integer)v.lastElement());

     

      if(v.contains(new Integer(3)))

         System.out.println("Vector contains 3.");

        

      // enumerate the elements in the vector.

      Enumeration vEnum = v.elements();

      System.out.println("\nElements in vector:");

     

      while(vEnum.hasMoreElements())

         System.out.print(vEnum.nextElement() + " ");

      System.out.println();

   }

}

 

 

Insertion operation

The methods which define in class Vector to perform insertion operations are listed in Table 3.

 

Method

Description

void addElement(E element)

The object specified by element is added to the vector.

void insertElementAt(E element,

int index)

Adds element to the vector at the location specified by index.

Table 4.21. The methods for insertion operations

 

Example 4.55.

The following program illustrates how to insert a specified element at the specified position using another version of the add() method.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)  {

        Vector v = new Vector(5);   // Create a default vector of size 5

 

        v.add(1, 1);

        v.add(2, 2);

        v.add(0, "Debasis");

        v.add(3, "Samanta");

        v.add(4, 3);

  v.add(5, 6.9);    // Vector will grow automatically

  

        System.out.println("Vector is " + v);

    }

}

 

 

 

Example 4.56.

The following program illustrates how to append all of the elements in the specified Collection to the end of this Vector.

 

import java.util.*;

 

class Vector_demo {

    public static void main(String[] arg)  {

        ArrayList arr = new ArrayList();

        arr.add(3);

        arr.add("geeks");

        arr.add("forgeeks");

        arr.add(4);

  

        // createn default vector

        Vector v = new Vector();

  

        // copying all element of array list int0 vector

        v.addAll(arr);

  

        // checking vector v

        System.out.println("vector v:" + v);

    }

}

 

Example 4.57.

The following program illustrates how to inserts all of the elements in the specified Collection into this Vector at the specified position.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)  {

        ArrayList arr = new ArrayList();

        arr.add(3);

        arr.add("Oracle");

        arr.add("Java");

        arr.add(4);

  

        // createn default vector

        Vector v = new Vector();

  

        v.add(2);

        // copying all element of array list int0 vector

        v.addAll(1, arr);

  

        // checking vector v

        System.out.println("vector v:" + v);

    }

}

 

Example 4.58.

The following program shows how to inserts the specified object as a component in this vector at the specified index.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // insert 10 at the index 7

        vec.insertElementAt(10, 7);

  

        // checking vector

        System.out.println(" Vector: " + vec);

    }

}

 

 

Deletion operations

The methods which define in class Vector to perform deletion operations are listed in Table 4.22.

 

Method

Description

void removeAllElements( )

Empties the vector. After this method executes, the size of the vector is zero.

boolean removeElement(Object element)

Removes element from the vector. If more than one instance of the specified object exists in the vector, then it is the first one that is removed. Returns true if successful and false if the object is not found.

void removeElementAt(int index)

Removes the element at the location specified by index.

Table 4.22. The methods for deletion operations

 

 

Example 4.59.

The following program illustrates how to remove all of the elements from a vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)  {

  

        Vector v = new Vector(); // The initial size of the vector is 10

  

        v.add(0, 1);

        v.add(1, 2);

        v.add(2, "IIT");

        v.add(3, "Kharagpur");

        v.add(4, 3);

  

        System.out.println("Vector is: " + v);

  

        v.clear();  // Clearing the vector

  

        System.out.println("after clearing: " + v); // checking vector

    }

}

 

Example 4.60.

The following program shows how to remove the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Java");

        v.add("C++");

        v.add(4);

  

        // removing first occurrence element at 1

        v.remove(1);

  

        // checking vector

        System.out.println("after removal: " + v);

    }

}

 

Example 4.61.

The following program shows how to  read the last components from a vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // checking last element of vector

        System.out.println("vector's last componenets: " + vec.lastElement());

    }

}

 

 

 

Example 4.62.

The following program shows how to retain only the elements in this Vector that are contained in the specified Collection.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

        Vector vecretain = new Vector(4);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // this elements will be retained

        vecretain.add(5);

        vecretain.add(3);

        vecretain.add(2);

  

        System.out.println("Calling retainAll()");

        vec.retainAll(vecretain);

  

        // let us print all the elements available in vector

        System.out.println("Numbers after removal :- ");

  

        Iterator itr = vec.iterator();

  

        while (itr.hasNext()) {

            System.out.println(itr.next());

        }

    }

}

 

Example 4.63.

The following program shows how to  remove all components from this vector and sets its size to zero.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // remove all elements

        vec.removeAllElements();

  

        // checking vector's size

        System.out.println("Size: " + vec.size());

  

        // checking vector's componenets

        System.out.println("vector's componenets: " + vec);

    }

}

 

 

Example 4.64.

The following program shows how to remove the first occurrence of the argument from this vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // Use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

        vec.add(5);

  

        // Remove an element

        vec.removeElement(5);

  

        // Checking vector

        System.out.println("Vector after removal: " + vec);

    }

}

 

 

Accessing elements in a vector

The miscellaneous methods defined in class Vector to perform deletion operations are listed in Table 4.23.

 

Method

Description

int capacity( )

Returns the capacity of the vector.

boolean contains(Object element)

Returns true if element is contained by the vector, and returns false if it is not.

E elementAt(int index)

Returns the element at the location specified by index.

Enumeration<E> elements( )

Returns an enumeration of the elements in the vector.

void ensureCapacity(int size)

Sets the minimum capacity of the vector to size.

E firstElement( )

Returns the first element in the vector.

int indexOf(Object element)

Returns the index of the first occurrence of element. If the object is not in the vector, –1 is returned.

int indexOf(Object element, int start)

Returns the index of the first occurrence of element at or after start. If the object is not in that portion of the vector, –1 is returned.

boolean isEmpty( )

Returns true if the vector is empty, and returns false if it contains one or more elements.

E lastElement( )

Returns the last element in the vector.

int lastIndexOf(Object element)

Returns the index of the last occurrence of element. If the object is not in the vector, –1 is returned.

int lastIndexOf(Object element,

int start)

Returns the index of the last occurrence of element before start. If the object is not in that portion of the vector, –1 is returned.

void setElementAt(E element,

int index)

The location specified by index is assigned element.

int size( )

Returns the number of elements currently in the vector.

Table 4.23: Methods in class Vector

 

Example 4.65.

The following program shows to check if a specific element is present in a vector or not.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg) {

  

        // create default vector

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Hi!");

        v.add("Buddy");

        v.add(3);

  

        // check whether vector contains "Java"

        if (v.contains("Java"))

            System.out.println("The element exists");

        else

            System.out.println("The element does notexist");

    }

}

 

 

 

Example 4.66.

The following program shows how to increase the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg) {

  

        Vector v = new Vector();

 

        v.ensureCapacity(22);   // ensuring capacity

  

        // cheking capacity

        System.out.println("Minimum capacity: " + v.capacity());

    }

}

 

Example 5.67.

The following program shows how to returns the element at the specified position in this Vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)  {

  

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Oracle");

        v.add("Java");

        v.add(4);

  

        // get the element at index 2

        System.out.println("element at index 2 is: " + v.get(2));

    }

}

 

 

Example 4.68.

The following program shows how to return the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Debasis");

        v.add("Samanta");

        v.add(4);

  

        // get the element at index of Geeks

        System.out.println("index of Geeks is: " + v.indexOf("Geeks"));

    }

}

 

Example 4.69.

The following program shows how to test if this vector has no element.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Oracle");

        v.add("Java");

        v.add(4);

  

        v.clear();

  

        // check whether vector is empty or not

        if (v.isEmpty())

            System.out.println("Vector is clear");

    }

}

 

Example 4.70.

The following program shows how to return the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg) {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Oracle");

        v.add("Java");

        v.add(4);

  

        // checking last occurrence of 2

        System.out.println("last occurrence of 2 is: " + v.lastIndexOf(2));

    }

}

Example 4.71.

The following program shows how to return the first component (the item at index 0) of this vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("India");

        v.add("NPTEL");

        v.add(4);

  

        // first element of vector

        System.out.println("first element of vector is: " + v.firstElement());

    }

}

 

Example 4.72.

The following program shows how to the size of a vetcor.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Debasis");

        v.add("Samanta");

        v.add(4);

  

        // setting new size of vector

        v.setSize(13);

  

        // size of vector

        System.out.println("size of vector: " + v.size());

    }

}

 

Example 4.73.

The following program shows how to return the number of components in this vector.

 

 import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Java");

        v.add("Oracle");

        v.add(4);

  

        // size of vector

        System.out.println(" size of vector: " + v.size());

    }

}

 

Example 4.74.

The following program shows how to set the component at the specified index of this vector to be the specified object.

 

 import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Mother");

        v.add("Merry");

        v.add(4);

  

        // set 4 at the place of 2

        v.setElementAt(4, 1);

  

        System.out.println("vector: " + v);

    }

}

 

 

Example 4.75.

The following program shows how to return the current capacity of this vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // checking capacity

        System.out.println("Capacity of vector: " + vec.capacity());

    }

}

 

Bulk operations on  vectors

The methods are shown in Table 4.24  are can be used for different bulk operations.

 

Method

Description

Object clone( )

Returns a duplicate of the invoking vector.

void copyInto(Object array[ ])

The elements contained in the invoking vector are copied into the array specified by array.

Enumeration<E> elements( )

Returns an enumeration of the elements in the vector.

String toString( )

Returns the string equivalent of the vector.

void trimToSize( )

Sets the vector’s capacity equal to the number of elements that it currently holds.

Table 4.24: The different methods defined in vector class.

 

Example 4.76.

The following program illustrates a cloning of a vector.

 

class Vector_demo {

    public static void main(String[] arg) {

  

        Vector v = new Vector();

  

        Vector v_clone = new Vector();

  

        v.add(0, 1);

        v.add(1, 2);

        v.add(2, "Oracle");

        v.add(3, "Java");

        v.add(4, 3);

  

        v_clone = (Vector)v.clone();

  

        System.out.println("Clone of v: " + v_clone);

    }

}

 

Example 4.77.

The following program shows how to copy the components of this vector into the specified array.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        Integer[] arr = new Integer[7];

  

        // copy componnent of vector int array arr

        vec.copyInto(arr);

  

        System.out.println("elements in array arr: ");

        for (Integer num : arr) {

            System.out.println(num);

        }

    }

}

 

 

Example 4.78.

The following program shows how to compare the specified Object with this Vector for equality.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg) {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Geeks");

        v.add("forGeeks");

        v.add(4);

  

        // second vector

        Vector v_2nd = new Vector();

  

        v_2nd.add(1);

        v_2nd.add(2);

        v_2nd.add("Geeks");

        v_2nd.add("forGeeks");

        v_2nd.add(4);

  

        if (v.equals(v_2nd))

            System.out.println("both vectors are equal");

    }

}

 

 

Example 4.79.

The following program shows how to trim the capacity of this vector to be the vector’s current size

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Geeks");

        v.add("forGeeks");

        v.add(4);

  

        // checking initial capacity

        System.out.println("Initial capacity: " + v.capacity());

  

        // trim capacity to size

        v.trimToSize();

  

        // checking capacity after triming

        System.out.println("capacity after triming: " + v.capacity());

    }

}

 

Example 4.80.

The following program shows how the toString() method is used to return a string representation of this Vector, containing the String representation of each element.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)  {

  

        // create default vector of capacity 10

        Vector v = new Vector();

  

        v.add(1);

        v.add(2);

        v.add("Geeks");

        v.add("forGeeks");

        v.add(4);

  

        // string equivalent of vector

        System.out.println(" String equivalent of vector: " + v.toString());

    }

}

 

Example 4.88.

The following program shows how to return an array representation of this Vector, containing the String representation of each element.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

  

        String elements[] = { "M", "N", "O", "P", "Q" };

        Set set = new HashSet(Arrays.asList(elements));

  

        String[] strObj = new String[set.size()];

  

        strObj = (String[])set.toArray(strObj);

  

        for (int i = 0; i < strObj.length; i++) {

            System.out.println(strObj[i]);

        }

        System.out.println(set);

    }

}

 

Example 4.89.

The following program shows how to return the hash code value for this Vector.

 

import java.util.*;

class Vector_demo {

    public static void main(String[] arg)

    {

        Vector vec = new Vector(7);

  

        // use add() method to add elements in the vector

        vec.add(1);

        vec.add(2);

        vec.add(3);

        vec.add(4);

        vec.add(5);

        vec.add(6);

        vec.add(7);

  

        // checking hash code

        System.out.println("Hash code: " + vec.hashCode());

    }

}